import utime as time
import app_server_aliyun
from driver import UART
import _thread
import app_relay
import app_config
import ujson
import app_config


result={}
rs232_flag=False
rs485_flag=False
rs485_writeBuf=b''
rs232_writeBuf=b''


def recv_data(data):
    global result
    result=data
    pass


def wait_input_cmd(id):
    while True:
        try:
            inputcmd = input('please input cmd:')
            inputcmd_dict = ujson.loads(inputcmd)
            if isinstance(inputcmd_dict,dict):
                if 'aliyun_config' in inputcmd_dict and isinstance(inputcmd_dict['aliyun_config'],dict):
                    if "deviceName" and "productKey"  and "productSecret" and "heartBeat" and "region" in inputcmd_dict["aliyun_config"] :
                        app_config.write_read_cfg(inputcmd_dict)
                        reboot()
                    else:
                        print("some is None:%s"%inputcmd_dict)

                if 'rs232' in inputcmd_dict and isinstance(inputcmd_dict['rs232'],dict):
                    if "enable" and "dataWidth" and "baudRate" and "stopBits" and "parity" in inputcmd_dict["rs232"]:
                        app_config.write_read_board(inputcmd_dict)
                        app_config.write_read_cfg(inputcmd_dict)
                        reboot()
                    else:
                        print("some is None:%s"%inputcmd_dict)                        

                if 'rs485' in inputcmd_dict and isinstance(inputcmd_dict['rs485'],dict):
                    if "enable" and "dataWidth" and "baudRate" and "stopBits" and "parity" in inputcmd_dict["rs485"]:
                        app_config.write_read_board(inputcmd_dict)
                        app_config.write_read_cfg(inputcmd_dict)
                        reboot()
                    else:
                        print("some is None:%s"%inputcmd_dict)

                if 'basecfg' in inputcmd_dict and isinstance(inputcmd_dict['basecfg'],dict):
                    if "adcType" and "uploadInterval" and "name" and "id"  and "aimode1" and "dimode1" and "aimode2" and "dimode2" in inputcmd_dict["basecfg"]:
                        app_config.write_read_cfg(inputcmd_dict)
                        reboot()
                    else:
                        print("some is None:%s"%inputcmd_dict)

                if 'ask' in inputcmd_dict and isinstance(inputcmd_dict['ask'],dict):
                    if "basedata" in  inputcmd_dict["ask"] and inputcmd_dict["ask"]["basedata"]=="1":
                        result=app_config.write_read_cfg(inputcmd_dict)
                        print(result)                        
                    elif "basecfg" in inputcmd_dict["ask"] and inputcmd_dict["ask"]["basecfg"]=="1":
                        result=app_config.write_read_cfg(inputcmd_dict)
                        print(result)
                    elif "aliyuncfg" in inputcmd_dict["ask"] and inputcmd_dict["ask"]["aliyuncfg"]=="1":
                        result=app_config.write_read_cfg(inputcmd_dict)
                        print(result)                        
                    elif "comcfg" in inputcmd_dict["ask"] and inputcmd_dict["ask"]["comcfg"]=="1":
                        result=app_config.write_read_cfg(inputcmd_dict)
                        print(result)                        
                if 'relay' in inputcmd_dict and isinstance(inputcmd_dict['relay'],dict):
                    # 控制继电器
                    if inputcmd_dict["relay"]["port"] is not None and inputcmd_dict["relay"]["state"] is not None:
                        app_relay.relay_ctl(inputcmd_dict["relay"]["port"],inputcmd_dict["relay"]["state"])
                        app_server_aliyun.update("relay1",app_relay.get_relay_state(1))      
                        app_server_aliyun.update("relay2",app_relay.get_relay_state(2))  
  
                    else:
                        print("some is None:%s"%inputcmd_dict)
                if 'reboot' in inputcmd_dict and isinstance(inputcmd_dict['reboot'],dict):
                    if inputcmd_dict["reboot"]["res"] is not None and inputcmd_dict["reboot"]["res"]=="1" :
                        reboot()
                if 'restore' in inputcmd_dict and isinstance(inputcmd_dict['restore'],dict):
                    if inputcmd_dict["restore"]["res"] is not None  and inputcmd_dict["restore"]["res"]=="1":                  
                        # 恢复出厂设置
                        pass                  
            else:
                print("imput cmd is not a dict")
            
            pass
        except ValueError:
            '''other cmd process'''
            print('input cmd is:' + inputcmd)
            pass
        except KeyboardInterrupt:
            _thread.exit()

        finally:
            pass


def rs232_data_from_cloud(data):
    global rs232_writeBuf
    rs232_writeBuf=str.encode(data)

def rs232_data_interaction(id):
    global result,rs232_writeBuf
    data=""
    stop_recv_flag=False
    if result["rs232"]["enable"]==1:
        rs232=UART()
        rs232.open("rs232")
        readBuf=bytearray(1024)  
        while True:
            if len(rs232_writeBuf)!=0:
                rs232.write(rs232_writeBuf)
                time.sleep_ms(10)
                rs232_writeBuf=b''
            else:
                size=rs232.read(readBuf)
                if size!=0:
                    # print(readBuf)
                    data+=readBuf.decode()[:readBuf.decode().find("\x00")]
                    # print("yyyyy",data)
                    stop_recv_flag=False
                elif size==0:
                    stop_recv_flag=True
                
                if stop_recv_flag==True and len(data) !=0:
                    # print("xxxxx:",data)
                    app_server_aliyun.update("232RecvData",data)
                    data=""
                    pass
                time.sleep_ms(result["subcontractInterval"])
            
def rs485_data_from_cloud(data):
    global rs485_writeBuf
    rs485_writeBuf=str.encode(data)

def rs485_data_interaction(id):
    global result,rs485_writeBuf
    data=""
    stop_recv_flag=False
    if result["rs485"]["enable"]==1:
        rs485=UART()
        rs485.open("rs485")
        readBuf=bytearray(1024)  
       

        while True:
            if len(rs485_writeBuf)!=0:
                rs485.write(rs485_writeBuf)
                time.sleep_ms(10)
                rs485_writeBuf=b''

            else:
                size=rs485.read(readBuf)
                if size!=0:
                    # print(readBuf)
                    data+=readBuf.decode()[:readBuf.decode().find("\x00")]
                    # print("yyyyy",data)
                    stop_recv_flag=False
                elif size==0:
                    stop_recv_flag=True
                
                if stop_recv_flag==True and len(data) !=0:
                    # print("xxxxx:",data)
                    app_server_aliyun.update("485RecvData",data)
                    data=""
                    pass
                time.sleep_ms(result["subcontractInterval"])


def uart_thread():
    _thread.start_new_thread(rs485_data_interaction,(2,))
    _thread.start_new_thread(rs232_data_interaction,(3,))
    _thread.start_new_thread(wait_input_cmd,(4,))




    